
const Util = require('Util');


cc.Class({
    extends: cc.Component,

    properties: {

    },

    onLoad() {
        this.cards = [];
        this.maxLen = 6;
    },

    addCard(card) {
        card.node.parent = this.node;
        card.zIndex = 0;

        let lastCard = this.getLastCard();
        if (lastCard) {
            card.x = lastCard.x;
            card.y = lastCard.y - lastCard.height / 2;
        } else {
            card.x = 0;
            card.y = 0;
        }

        this.cards.push(card);

        this.matchCard(this.cards.length - 1);
    },
    removeCard(idx) {
        let card = this.cards[idx];
        card.node.destroy();

        this.cards.splice(idx, 1);
    },
    eraseCard(idx) {
        let card = this.cards[idx];
        let cardSpace = card.height / 2;

        this.removeCard(idx);

        for (let i = idx, len = this.cards.length; i < len; i++) {
            let card = this.cards[i];
            card.y += cardSpace;
        }

        this.matchCard(this.cards.length - 1);
    },
    getLastCard() {
        return this.cards[this.cards.length - 1];
    },

    findCardIndexByPos(pos) {
        pos = this.node.convertToNodeSpaceAR(pos);

        for (let i = this.cards.length - 1; i >= 0; i--) {
            let card = this.cards[i];
            if ( cc.rectContainsPoint(card.getBox(), pos) ) {
                return i;
            }
        }

        return -1;
    },

    matchCard(idx) {
        let cards = this.cards;

        let card = cards[idx];
        let prevCard = cards[idx - 1];
        if (prevCard && prevCard.num == card.num) {
            prevCard.setNum(prevCard.num * 2, () => {
                this.node.emit('match_card');

                this.removeCard(idx);

                this.matchCard(idx - 1);
            });
        }

        // let idx = cards.length - 1;
        // let card = cards[idx];
        // let prevCard;
        // while (prevCard = cards[idx - 1]) {
        //     if (prevCard.num == card.num) {
        //         prevCard.setNum(prevCard.num * 2);
        //         this.removeCard(idx);
        //
        //         card = prevCard;
        //         idx--;
        //     } else {
        //         break;
        //     }
        // }
    },

    isFull() {
        return this.cards.length == this.maxLen;
    },

    containsPoint(p) {
        p = this.node.parent.convertToNodeSpaceAR(p);

        let box = this.node.getBoundingBox();
        let lastCard = this.cards[this.cards.length - 1];
        if (lastCard) {
            let cardHeight = -lastCard.getBox().y - box.height / 2;
            box.y -= cardHeight;
            box.height += cardHeight;
        }

        return cc.rectContainsPoint(box, p);
    }
});
